﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.Events;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;

namespace Windows.UI.Notifications
{
    [Shared]
    [MessageRecipientExport("BadgeNotificationMessageProcessor", typeof(UpdateBadgeNotificationMessage))]
    //[PartMetadata("Name","BadgeNotificationMessageProcessor")]
    //[PartMetadata("MessageType", typeof(UpdateBadgeNotificationMessage))]
    //[Export(typeof(IMessageRecipient))]
    public class BadgeNotificationMessageProcessor : IMessageRecipient
    {

        //[Import(typeof(IEventPublisher), AllowDefault = true)]
        private IEventPublisher messenger;// { get; set; }

        [ImportingConstructor]
        public BadgeNotificationMessageProcessor([Import]IEventPublisher msgr)
        {
            messenger = msgr;
        }

        #region Privates

        private XmlDocument PrepareBadgeXml(BadgeTemplateType template, string value, DateTimeOffset? ExpirationTime)
        {
            XmlDocument badge = BadgeUpdateManager.GetTemplateContent(template);
            XmlNodeList imageElements = badge.GetElementsByTagName("badge");
            XmlElement imageElement = (XmlElement)imageElements.Item(0);
            imageElement.SetAttribute("value", value);
            return badge;
        }

        private void UpdateBadge(BadgeTemplateType template, string value, DateTimeOffset? ExpirationTime)
        {
            XmlDocument badgeXml = PrepareBadgeXml(BadgeTemplateType.BadgeNumber, value, ExpirationTime);
            BadgeUpdater updater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
            var badge = new BadgeNotification(badgeXml);
            badge.ExpirationTime = ExpirationTime;
            updater.Update(badge);
        }

        #endregion

        public void ProcessMessage(UpdateBadgeNotificationMessage message)
        {
            var data = message.Content;

            UpdateBadge(data.Template, data.Value, data.ExpirationTime);

            messenger.Publish<BadgeNotificationCreatedMessage>(new BadgeNotificationCreatedMessage(data));
        }

        public void ProcessMessage(object message)
        {
            if(message is UpdateBadgeNotificationMessage)
                ProcessMessage((UpdateBadgeNotificationMessage)message);
        }

        [OnImportsSatisfied]
        public void OnImportsSatisfied()
        {
        }

    }
}
